package com.ehotting.mqbd.core.service.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ehotting.eaf.core.text.UUID;
import com.ehotting.eaf.redis.service.RedisService;
import com.ehotting.mqbd.api.MQDBConstants;
import com.ehotting.mqbd.api.bean.MQBaseData;
import com.ehotting.mqbd.api.bean.MQDataAble;
import com.ehotting.mqbd.api.enums.SendTypeEnum;
import com.ehotting.mqbd.core.logger.MqMsgLogger;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component("redisMqStorage")
public class RedisMqStorage implements MqStorageAble {

    private static final Logger logger = LoggerFactory.getLogger(RedisMqStorage.class);

    @Autowired
    protected MqMsgLogger mqMsgLogger;

    @Autowired
    private RedisService redisService;

    public <T> void put(String key, T msg) {
        redisService.setCacheObject(MQDBConstants.STORAGE + key,
                msg,
                 5L,
                TimeUnit.DAYS);
    }

    public <T> T get(String key) {
        T t = redisService.getCacheObjectAndDelete(MQDBConstants.STORAGE +key);
        return t;
    }

    public void handlePut(MQDataAble data){
        MQBaseData baseData = (MQBaseData)data;
        if(ArrayUtils.contains(data.getSendType(), SendTypeEnum.REDIS_REQUEST_BODY)){
            if(baseData.getRequest()!=null){
                baseData.setRequestIndex(UUID.getUUID());
                this.put(baseData.getRequestIndex(),baseData.getRequest());
                baseData.setRequest(null);
                baseData.setRequestString(null);
            }
        }

        if(ArrayUtils.contains(data.getSendType(),SendTypeEnum.REDIS_RESPONSE_BODY)) {
            if(baseData.getResponse()!=null){
                baseData.setResponseIndex(UUID.getUUID());
                this.put(baseData.getResponseIndex(),baseData.getResponse());
                baseData.setResponse(null);
                baseData.setResponseString(null);
            }
        }

    }

    public MQDataAble handleGet(MQDataAble data){
        logger.info("Start handleGet");
        MQBaseData baseData = (MQBaseData)data;
        if(ArrayUtils.contains(data.getSendType(), SendTypeEnum.REDIS_REQUEST_BODY)){
            baseData.setRequest(this.get(baseData.getRequestIndex()));
            mqMsgLogger.info("->:{}",JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect));
        }

        if(ArrayUtils.contains(data.getSendType(),SendTypeEnum.REDIS_RESPONSE_BODY)) {
            baseData.setResponse(this.get(baseData.getResponseIndex()));
            mqMsgLogger.info("<-:{}",JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect));
        }
        logger.info("Finish handleGet");
        return baseData;
    }

}
